﻿#include <stdio.h>
#include <string.h>
#include <malloc.h>

char u16[20] = { 0 };
char uu[20] = { 0 };
char* U8_to_U16(const char *arr,int len)
{
	unsigned char a1, a2, a3, a4, u16_4_code;
	int b;
	for (int i = 0; i < len; i++) {
		// 单字节  0xxxxxxx
		if (((arr[i] >> 7) & 0b1) == 0) {
			u16[i] = arr[i];
			printf("这是utf-8单字节字符: %c\n", arr[i]);
			printf("U+%04X\n", u16[i]);
		}
		else if ((((arr[i] >> 5) & 0b111) == 0b110)) {
			a1 = (arr[i] & 0x1F) << 6;
			a2 = arr[++i] & 0x3f;
			u16[i] = a1 | a2;
			printf("这是utf-8双字节字符: %c\n", arr[i]);
			printf("U+%04X\n", u16[i]);
		}
		else if (((arr[i] >> 4) & 0b1111) == 0b1110) {
			b = (arr[i] & 0xf) << 12;
			b|=(arr[++i] & 0x3f) << 6;
			b|= arr[++i] & 0x3f;
			printf("这是utf-8三字节字符: %c\n", arr[i]);
			printf("U+%04X\n", b);
		}
		// 四字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
		else if (((arr[i] >> 3) & 0b11111) == 0b11110) {
			b= (arr[i] & 0x7) << 18;
			b|= (arr[++i] & 0x3f) << 12;
			b|= (arr[++i] & 0x3f) << 6;
			b|= arr[++i] & 0x3f;
			u16_4_code = (b - 0x10000<<10) & 0x3ff|0xd800;
			u16_4_code = (b - 0x10000);
			b= (((u16_4_code >> 10)) | 0xd800) << 16;
			b|= ((u16_4_code & 0x3ff) | 0xdc00);
			printf("这是utf-8四字节字符: %c\n", b);
			//以十六进制格式打印变量unicode的值
			printf("U+%04X\n", b);
		}
	}
	return u16;
}
int main() 
{
	const char *s1 = u8"00猫🍌";
	for (int i = 0; i < sizeof(s1) / sizeof(char); i++) 
	{
		printf("%c", s1[i]);
	}
	printf("\n");
	int len = sizeof(s1) / sizeof(char);
	U8_to_U16(s1, len);
	int d = 0;
	scanf_s("%d", &d);
	return 0;
}

